//
//  RecordVolumeViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/6/9.
//

#import "RecordVolumeViewController.h"
#import "SeeAudio.h"
#import "AVPlayerManager.h"
#import "CustomLineView.h"
#import "UIView_extension.h"
#import "FileManager.h"
#import "MNControl.h"
#import "LocalRecordModel.h"
#import "GlobalFunction.h"

@interface RecordVolumeViewController ()<AVPlayerDelegate, UIScrollViewDelegate, UIGestureRecognizerDelegate> {
    CGFloat duration;
    CGFloat currentTime;
    BOOL isDragging;
    NSString *outPath;
    NSString *recordName;
}
@property (weak, nonatomic) IBOutlet UIImageView *bg;
@property (weak, nonatomic) IBOutlet UIScrollView *waveScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *actionBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (nonatomic, strong) CustomLineView *line;
@property (nonatomic, strong) MNControl *slider;
@property (nonatomic, strong) NSMutableArray *audioMixParams;

@end

@implementation RecordVolumeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"音量";
    [self addBackBtn];
    [((UIButton *)[self addRigthBtn:@"完成"]) addTarget:self action:@selector(donePress) forControlEvents:UIControlEventTouchUpInside];
    [self initView];
    [self.scrollView addSubview:self.slider];

    if (self.model.needSaveUrl) {
        [self seeAudio:self.model.needSaveUrl];
    } else {
        [self seeAudio:[NSURL fileURLWithPath:[[FileManager sharedManager] getLocalFilePath:self.model.fileName]]];
    }
    NSString *recordName = dateTurnTimeNameStr([NSDate date]);
    outPath = [AVPlayerManager getTmpRecordName:[NSString stringWithFormat:@"%@.m4a", recordName]];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [AVPlayerManager manager].delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[AVPlayerManager manager] pause];
    [AVPlayerManager manager].delegate = nil;
}

- (void)donePress {
    if (self.ReloadHandle) {
        self.ReloadHandle([NSURL fileURLWithPath:outPath], self.title);
    }
    [self goBackAction];
}

- (IBAction)actionPress {
    self.actionBtn.selected = !self.actionBtn.selected;
    if (!self.actionBtn.selected) {
        [[AVPlayerManager manager] pause];
    } else {
        [[AVPlayerManager manager] play];
    }
}

- (IBAction)resetPress {
    self.actionBtn.selected = NO;
    [[AVPlayerManager manager] pause];
    self.slider.currentIndex = 10;
}

- (void)seeAudio:(NSURL *)url {
    [[AVPlayerManager manager] setAVPlayerURL:url];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.waveScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    });
    
    AVURLAsset  *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
    self->duration = CMTimeGetSeconds(asset.duration);
    __weak __typeof(self) weakSelf = self;
    [SeeAudio renderPNGAudioPictogramLogForAsset:asset done:^(UIImage *spectrumImage,UIImage *scaleImage,NSInteger imageWidth) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideHudAlert];
            [weakSelf.waveScrollView setContentSize:CGSizeMake(imageWidth, 0)];
            UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imageWidth, 280)];
            imgv.image = spectrumImage;
            [weakSelf.waveScrollView addSubview:imgv];
            UIImageView *scaleImgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 280, imageWidth, 30)];
            scaleImgv.image = scaleImage;
            [weakSelf.waveScrollView addSubview:scaleImgv];
            
        });
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    isDragging = YES;
    [[AVPlayerManager manager] pause];
    self.actionBtn.selected = NO;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    isDragging = NO;
    [[AVPlayerManager manager] seekToTimeInterval:currentTime];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [[AVPlayerManager manager] seekToTimeInterval:currentTime];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.waveScrollView == scrollView) {
        currentTime = (scrollView.contentOffset.x/(scrollView.contentSize.width-SCREEN_WIDTH_DEVICE))*duration;
        if (currentTime > duration) {
            currentTime = duration;
        } else if (currentTime <= 0) {
            currentTime = 0;
        }
        int currentMin  = (int)currentTime / 60;
        int currentSecond  = (int)currentTime % 60;
        int millisecond = (currentTime - currentSecond)*100 - currentMin*60*100;
        NSString *currentTime1 = [NSString stringWithFormat:@"%.2d:%.2d.%02d",currentMin,currentSecond, millisecond];
        self.timeLabel.text = currentTime1;
    }
}

#pragma mark ---AVPlayerDelegate---
- (void)timeRunAndTime:(double)runTime andValue:(NSString *)value andScale:(CGFloat)scale {
    currentTime = runTime;
    self.timeLabel.text = value;
    if ([AVPlayerManager manager].isPlaying) {
        CGFloat pointX = (self.waveScrollView.contentSize.width-SCREEN_WIDTH_DEVICE)*scale;
        if (pointX < self.waveScrollView.contentOffset.x) {
            pointX = self.waveScrollView.contentOffset.x;
        }
        [UIView animateWithDuration:0.1 animations:^{
            [self.waveScrollView setContentOffset:CGPointMake(pointX, 0) animated:NO];
        }];
    }
}

- (void)trackPlayDidEnd {
    self.actionBtn.selected = NO;
    [self.waveScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)initView {
    [self.bg setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight + 280, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - (IS_iPhoneX_Top + NavBarHeight + 280))];
    [self.scrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight + 310, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Bottom - IS_iPhoneX_Top - NavBarHeight - 50 - 310)];
    [self.scrollView setContentSize:CGSizeMake(0, 300)];
    [self.waveScrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, 310)];
    [self.view addSubview:self.line];
}


- (void)exportAudioWithURL:(NSString *)audioPath {
    AVMutableComposition *composition =[AVMutableComposition composition];
    _audioMixParams =[NSMutableArray arrayWithCapacity:0];
    //录制的视频
    NSURL *audio_inputFileUrl = [NSURL fileURLWithPath:audioPath];
    AVURLAsset *bgAudioAsset = [AVURLAsset URLAssetWithURL:audio_inputFileUrl options:nil];
    
    CMTime startTime = CMTimeMakeWithSeconds(0,bgAudioAsset.duration.timescale);
    CMTime trackDuration = bgAudioAsset.duration;
    
    //获取音频素材
    [self setUpAndAddAudioAtPath:audio_inputFileUrl toComposition:composition start:startTime dura:trackDuration volume:(self.slider.currentIndex/10.0) offset:CMTimeMake(0,44100)];
    
    
    //创建一个可变的音频混合
    AVMutableAudioMix *audioMix  =[AVMutableAudioMix audioMix];
    audioMix.inputParameters = [NSArray arrayWithArray:_audioMixParams];//从数组里取出处理后的音频轨道参数
    
    //创建一个输出
    AVAssetExportSession *exporter =[[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetAppleM4A];
    //存储的具体路径
    if([[NSFileManager defaultManager]fileExistsAtPath:outPath]) {
        [[NSFileManager defaultManager]removeItemAtPath:outPath error:nil];
    }
    exporter.audioMix = audioMix;
    exporter.outputFileType = AVFileTypeAppleM4A;
    exporter.outputURL = [NSURL fileURLWithPath:outPath];
    exporter.shouldOptimizeForNetworkUse = YES;   //优化网络
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        //完成输出后打印出输出的各种状态
        switch (exporter.status) {
            case AVAssetExportSessionStatusFailed:{
                NSError *exportError = exporter.error;
                NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);
            }break;
            case AVAssetExportSessionStatusCompleted:{
                NSLog (@"AVAssetExportSessionStatusCompleted");
                NSLog(@"---  %@",self->outPath);
                [self seeAudio:[NSURL fileURLWithPath:self->outPath]];
            }break;
            case AVAssetExportSessionStatusUnknown: NSLog (@"AVAssetExportSessionStatusUnknown"); break;
            case AVAssetExportSessionStatusExporting: NSLog (@"AVAssetExportSessionStatusExporting"); break;
            case AVAssetExportSessionStatusCancelled: NSLog (@"AVAssetExportSessionStatusCancelled"); break;
            case AVAssetExportSessionStatusWaiting: NSLog (@"AVAssetExportSessionStatusWaiting"); break;
            default:  NSLog (@"didn't get export status"); break;
        }
    }];
}

//通过文件路径建立和添加音频素材
- (void)setUpAndAddAudioAtPath:(NSURL*)assetURL toComposition:(AVMutableComposition*)composition start:(CMTime)start dura:(CMTime)dura volume:(CGFloat)volume offset:(CMTime)offset{
    AVURLAsset *songAsset =[AVURLAsset URLAssetWithURL:assetURL options:nil];
    AVMutableCompositionTrack *track =[composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    AVAssetTrack *sourceAudioTrack =[[songAsset tracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0];
    NSError *error =nil;
    BOOL ok =NO;
    CMTime startTime = start;
    CMTime trackDuration = dura;
    CMTimeRange tRange =CMTimeRangeMake(startTime,trackDuration);
    //设置音量
    //AVMutableAudioMixInputParameters（输入参数可变的音频混合）
    //audioMixInputParametersWithTrack（音频混音输入参数与轨道）
    AVMutableAudioMixInputParameters *trackMix =[AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:track];
    [trackMix setVolume:volume atTime:startTime];
    //素材加入数组
    [_audioMixParams addObject:trackMix];
    //Insert audio into track  //offsetCMTimeMake(0, 44100)
    ok = [track insertTimeRange:tRange ofTrack:sourceAudioTrack atTime:kCMTimeInvalid error:&error];
}

- (NSMutableArray *)audioMixParams{
    
    if (!_audioMixParams) {
        _audioMixParams = [NSMutableArray array];
    }
    
    return _audioMixParams;
}

- (CustomLineView *)line {
    if (!_line) {
        _line = [[CustomLineView alloc] initCustomView:CGRectMake((SCREEN_WIDTH_DEVICE-3)/2.0, IS_iPhoneX_Top + NavBarHeight, 3, 280)];
    }
    return _line;
}

- (MNControl *)slider {
    if (!_slider) {
        _slider = [[MNControl alloc] initWithFrame:CGRectMake(41, 215, SCREEN_WIDTH_DEVICE - 82, 40)];
        _slider.maxCount = 11;
        _slider.currentIndex = 10;
        _slider.hiddenDot = YES;
        __weak typeof(self) weakSelf = self;
        _slider.SliderHandle = ^(NSInteger index) {
            [[AVPlayerManager manager] pause];
            weakSelf.actionBtn.selected = NO;
            [weakSelf exportAudioWithURL:[[FileManager sharedManager] getLocalFilePath:weakSelf.model.fileName]];

        };
    }
    return _slider;
}
@end
